<template>
  <div class="fill">
    <my-dialog
      title="添加部门"
      :modelValue="data.dialogVisible"
      @update:modelValue="(val:any) => (data.dialogVisible = val)"
      @confirm="events.handleAddDepartment"
    >
      <el-form ref="formRef" label-width="80px" :model="data.form">
        <el-form-item label="上级部门">
          <el-tag>{{ data.currentNode?.name }}</el-tag>
        </el-form-item>
        <el-form-item
          label="名称"
          prop="name"
          :rules="[{ required: true, message: '请填写名称' }]"
        >
          <el-input
            maxlength="100"
            v-model="data.form.name"
            placeholder="请输入名称"
            type="text"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            maxlength="500"
            :rows="4"
            v-model="data.form.description"
            placeholder="请输入描述"
            type="textarea"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
    </my-dialog>
    <div class="flex">
      <el-scrollbar class="tree">
        <el-scrollbar class="tree-scrollbar"
          ><el-tree
            :data="data.treeData"
            highlight-current
            default-expand-all
            :current-node-key="data.currentNodeKey"
            @node-click="events.handleNodeClick"
            :expand-on-click-node="false"
            node-key="id"
            :props="{ label: 'name', children: 'children' }"
          ></el-tree
        ></el-scrollbar>
        <div class="tree-btn">
          <div>
            <el-button
              type="primary"
              size="small"
              class="block"
              @click="events.showAdd"
              >新增</el-button
            >
          </div>
        </div>
      </el-scrollbar>
      <div class="description">
        <el-descriptions :column="1" border label-width="20%">
          <template #title>
            <div class="description-header">
              <div class="description-title">部门详情</div>
            </div>
          </template>
          <template #extra>
            <div class="description-header">
              <template v-if="data.currentNode?.id">
                <el-popconfirm
                  confirm-button-text="是"
                  cancel-button-text="否"
                  title="是否要删除该部门?"
                  @confirm="events.handleDeleteDepartment"
                >
                  <template #reference>
                    <el-button type="danger" plain>删除</el-button>
                  </template>
                </el-popconfirm>
                <el-button type="warning" plain @click="events.showUpdate"
                  >修改</el-button
                >
              </template>
            </div>
          </template>
          <el-descriptions-item label="编号" label-align="right">
            {{ data.currentNode?.id }}
          </el-descriptions-item>
          <el-descriptions-item label="名称" label-align="right">
            {{ data.currentNode?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" label-align="right">
            {{ data.currentNode?.description }}
          </el-descriptions-item>
          <el-descriptions-item label="上级部门" label-align="right">
            {{ data.currentNode?.parentName }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" label-align="right">
            {{
              data.currentNode
                ? new Date(data.currentNode?.createTime).toLocaleString()
                : ''
            }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import {
  getDeprtmentTree,
  addDepartment,
  deleteDepartment,
} from '../../functions/department';
import MyDialog from '../../components/MyDialog.vue';
import { confirmBox, toast } from '../../utils/tools';

const formRef = ref<any>(null);

interface Data {
  treeData: any[];
  currentNodeKey: string | null;
  currentNode: any;
  dialogVisible: boolean;
  form: any;
}
const data = reactive<Data>({
  treeData: [],
  currentNodeKey: null,
  currentNode: null,
  dialogVisible: false,
  form: {},
});
const events = reactive({
  handleNodeClick: (d: any) => {
    if (data.currentNodeKey !== d.id) {
      data.currentNodeKey = d.id;
      data.currentNode = d;
    } else {
      data.currentNodeKey = null;
      data.currentNode = null;
    }
  },
  showUpdate: () => {},
  showAdd: () => {
    data.dialogVisible = true;
  },
  handleAddDepartment: async () => {
    formRef.value?.validate(async (valid: any) => {
      if (valid) {
        // 验证成功，发送数据
        if (data.currentNode?.id == null) {
          confirmBox('上级部门为空，是否确认添加？', async () => {
            const res = await addDepartment({
              ...data.form,
              parentId: data.currentNode?.id,
            });
            if (res.code >= 0) {
              data.dialogVisible = false;
              methods.resetForm();
              toast.success(res.message || '添加成功');
              await methods.bindTree();
            } else {
              toast.error(res.message || '添加失败');
            }
          });
        } else {
          const res = await addDepartment({
            ...data.form,
            parentId: data.currentNode.id,
          });
          if (res.code >= 0) {
            data.dialogVisible = false;
            methods.resetForm();
            toast.success(res.message || '添加成功');
            await methods.bindTree();
          } else {
            toast.error(res.message || '添加失败');
          }
        }
      } else {
        console.log('表单验证失败!');
        return false;
      }
    });
  },
  handleDeleteDepartment: async () => {
    const res = await deleteDepartment({ id: data.currentNode?.id });
    console.log(res);
    if (res.code >= 0) {
      toast.success(res.message || '删除成功');
      data.currentNodeKey = null;
      data.currentNode = null;
      await methods.bindTree();
    } else {
      toast.error(res.message || '删除失败');
    }
  },
});
const methods = reactive({
  bindTree: async () => {
    var res = await getDeprtmentTree();
    if (res.code >= 0) {
      data.treeData = res.data;
    }
  },
  resetForm: () => {
    formRef.value.resetFields();
  },
});
onMounted(async () => {
  await methods.bindTree();
});
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  height: 100%;
}
.tree {
  width: 25%;
  height: 100%;
  background-color: #f2f2f2;
  border-right: 1px solid #ccc;
}
.tree-scrollbar {
  height: 90%;
}
:deep(
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
  ) {
  background-color: #baf !important; /* 高亮背景色 */
  color: #fff; /* 字体颜色 */
  font-weight: bold; /* 字体加粗 */
}
.tree-btn {
  padding: 2%;
}
.description {
  width: 75%;
  height: 100%;
  background-color: #ffffff;
}
.description-title {
  padding: 8px;
  font-weight: bold;
}
.description-header {
  padding-top: 10px;
  padding-right: 10px;
}
</style>
